package geektime.concurrent.part1;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 模拟ReentrantLock的公平锁
 */
public class MyFairLock {
    // new ReentrantLock()默认是创建的非公平锁，如果指定构造方法中的参数为true则可以创建公平锁
    private ReentrantLock lock = new ReentrantLock(true);

    public void competeLock() {
        while (true) {
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + " hold");
            } finally {
                System.out.println(Thread.currentThread().getName() + " release");
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        int count = 4;
        MyFairLock myFairLock = new MyFairLock();
        Thread[] threads = new Thread[count];
        Runnable runnable = () -> {
            System.out.println(Thread.currentThread().getName() + " start");
            myFairLock.competeLock();
        };
        // 构造4个线程，让着四个线程内的runnable为同一个，这是就保证了lock的唯一性
        ThreadGroup threadGroup = new ThreadGroup("ThreadGroup");
        for (int i = 0; i < count; i++) {
            threads[i] = new Thread(threadGroup, runnable, "thread" + i);
        }
        // 依次启动和几个线程，让他们去竞争同一把锁，然后执行业务代码
        for (int i = 0; i < count; i++) {
            threads[i].start();
        }
    }
}
